<template>
  <div v-loading.fullscreen.lock="viewLoading">
    <CrudView
      :form-data="formData"
      :form-items="formItems"
      :btn-items="btnItems"
      :page-colums="pageColums"
      :page-data="{pageInfo, list}"
      :selection-change-handler="selectionChangeHandler"
    />
    <!-- 教师信息编辑/新增模态框  -->
    <el-dialog
      :title="modalTitle"
      :center="true"
      :visible.sync="showModal"
      :before-close="closeTeacherInfoModal"
    >
      <el-form :model="modalData" label-width="90px" :disabled="modalModel === 'Look'">
        <el-tabs v-model="activename">
          <el-tab-pane label="基本信息" name="first">
            <div style="max-height: 400px;overflow: auto">
              <el-form-item label="工号">
                <el-input v-model="modalData.workerNo" type="text" :disabled="true" placeholder="工号自动生成..." />
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="modalData.realName" type="text" />
              </el-form-item>
              <el-form-item label="性别">
                <el-select v-model="modalData.gender" placeholder="请选择性别">
                  <el-option label="男" value="男" />
                  <el-option label="女" value="女" />
                </el-select>
              </el-form-item>
              <el-form-item label="职称">
                <el-select v-model="modalData.teacherRank" placeholder="请选择职称">
                  <el-option label="助教" :value="0" />
                  <el-option label="讲师" :value="1" />
                  <el-option label="副教授" :value="2" />
                  <el-option label="教授" :value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="出生日期">
                <el-date-picker v-model="modalData.dateOfBirth" format="yyyy-MM-dd" value-format="yyyy-MM-dd" />
              </el-form-item>
              <el-form-item label="证件类型">
                <el-select v-model="modalData.idCardType" placeholder="请选择证件类型">
                  <el-option v-for="it in dropDownData.idCardType" :key="it.value" :label="it.label" :value="it.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="证件号码">
                <el-input v-model="modalData.idCardNumber" type="text" />
              </el-form-item>
              <el-form-item label="个人照片">
                <el-upload
                  class="avatar-uploader"
                  action
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="uploadTeaPhoto"
                >
                  <img v-if="modalData.photoUrl" :src="modalData.photoUrl | randUrl " class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="联系方式" name="second">
            <div style="max-height: 400px;overflow: auto">
              <el-form-item label="座机/手机号">
                <el-input v-model="modalData.phoneNum" type="text" />
              </el-form-item>
              <el-form-item label="电子邮箱">
                <el-input v-model="modalData.email" type="text" />
              </el-form-item>
              <el-form-item label="通讯地址">
                <el-input v-model="modalData.address" type="text" />
              </el-form-item>
              <el-form-item label="QQ号">
                <el-input v-model="modalData.qqNumber" type="text" />
              </el-form-item>
              <el-form-item label="微信号">
                <el-input v-model="modalData.wechatNumber" type="text" />
              </el-form-item>
              <el-form-item label="办公地址">
                <el-input v-model="modalData.workAddress" type="text" />
              </el-form-item>
              <el-form-item v-if="modalModel !== 'Look'">
                <el-button @click="modalCancelHandler">取消</el-button>
                <el-button type="primary" @click="modalSubmitHandler">提交</el-button>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

import CrudView from '@/components/CrudView'
import { getPage, getById, create, update, deleteByIds } from '@/api/ms/member/teacher'
import { getIdCardTypeDropDown } from '@/api/ms/dropdown'
import { uploadTeacherPhoto } from '@/api/ms/oss'

// vue对象钩子
let vueHook = null

function getDefaultModalData() {
  return { // 默认的教师信息编辑/新增modal框数据
    id: null,
    workerNo: '',
    realName: '',
    gender: '',
    dateOfBirth: '',
    idCardType: null,
    idCardNumber: '',
    photoUrl: '',
    TeacherRank: null,
    phoneNum: '',
    email: '',
    address: '',
    qqNumber: '',
    wechatNumber: '',
    workAddress: ''
  }
}

export default {
  name: 'Teacher',
  components: { CrudView },
  data() {
    return {
      viewLoading: false,
      formData: {
        workerNo: '',
        realName: '',
        gender: '',
        teacherRank: null
      },
      dropDownData: {
        idCardType: []
      },
      formItems: [
        { order: 1, label: '工号', type: 'Input', paramName: 'workerNo' },
        { order: 2, label: '姓名', type: 'Input', paramName: 'realName' },
        { order: 3, label: '性别', type: 'Select', paramName: 'gender', options: [
          { label: '男', value: '男' },
          { label: '女', value: '女' },
          { label: '所有', value: '' }
        ] },
        { order: 4, label: '职称', type: 'Select', paramName: 'teacherRank', options: [
          { label: '助教', value: 0 },
          { label: '讲师', value: 1 },
          { label: '副教授', value: 2 },
          { label: '教授', value: 3 }
        ] },
        { order: 5, type: 'Button', btnName: '查询', clickHandler: () => {
          vueHook.ignoreRefresh = true
          vueHook.pageInfo.pageNum = 1
          vueHook.refreshTeacherInfo()
        }
        }
      ],
      btnItems: [
        { order: 1, name: '查看', type: 'primary', clickHandler: () => vueHook.openTeacherInfoModal('Look') },
        { order: 2, name: '编辑', type: 'warning', clickHandler: () => vueHook.openTeacherInfoModal('Edit') },
        { order: 3, name: '添加', type: 'success', clickHandler: () => vueHook.openTeacherInfoModal('Create') },
        { order: 4, name: '删除', type: 'danger', clickHandler: () => vueHook.batchDeleteTeacher() }
      ],
      pageColums: [
        { label: '工号', propName: 'workerNo' },
        { label: '姓名', propName: 'realName' },
        { label: '性别', propName: 'gender' },
        { label: '职称', propName: 'teacherRankShow' },
        { label: '证件类型', propName: 'idCardTypeShow' },
        { label: '证件号码', propName: 'idCardNumber' },
        { label: '出生日期', propName: 'dateOfBirth' }
      ],
      pageInfo: {
        pageNum: 1, // 当前页
        pageSize: 10, // 每页行数
        total: 1000 // 列表总行数
      },
      selectionChangeHandler: (srows) => { // 记录选择改变handler
        vueHook.ids = srows.map(i => i.id)
      },
      list: [], // 数据列表
      ignoreRefresh: false,
      ids: [], // 选中的id列表
      showModal: false, // modal框显示标识
      modalTitle: '', // modal标题
      modalModel: 'Look', // modal状态 ，分别为 Look、Edit、Create
      activename: 'first',
      modalData: { // 教师信息编辑/新增modal框数据
        id: null,
        workerNo: '',
        realName: '',
        gender: '',
        dateOfBirth: '',
        idCardType: null,
        idCardNumber: '',
        photoUrl: '',
        teacherRank: null,
        phoneNum: '',
        email: '',
        address: '',
        qqNumber: '',
        wechatNumber: '',
        workAddress: ''
      }
    }
  },
  computed: {
    pageParam() {
      const { workerNo, realName, gender, teacherRank } = this.formData
      const pageInfo = this.pageInfo
      return { workerNo, realName, gender, teacherRank, pageInfo }
    }
  },
  watch: {
    pageInfo: {
      handler(val) {
        if (this.ignoreRefresh) {
          // 需要忽略本次change
          this.ignoreRefresh = false
          return
        }
        // 向后台请求新的表格数据
        this.refreshTeacherInfo()
      },
      deep: true
    }
  },
  mounted() {
    // 暴露vue对象
    vueHook = this
    // 请求下拉框数据
    this.refreshDropDown()
    // 向后台请求新的表格数据
    this.refreshTeacherInfo()
  },
  methods: {
    // 刷新表单下拉框数据
    refreshDropDown() {
      getIdCardTypeDropDown().then(({ data }) => {
        this.dropDownData.idCardType = data
      }).catch((err) => console.log(err))
    },
    // 刷新教师列表数据
    refreshTeacherInfo() {
      getPage(this.pageParam).then(({ list, pageInfo }) => {
        this.ignoreRefresh = true
        this.list = list
        this.pageInfo = pageInfo
      }).catch((err) => {
        console.log(err)
        this.$message.error('查询教师列表数据出错')
      })
    },
    // 打开教师信息编辑/新增modal
    openTeacherInfoModal(model) {
      // 如果是Create操作，直接打开modal
      if (model === 'Create') {
        // 打开modal
        this.modalTitle = '教师信息创建'
        this.modalModel = model
        this.showModal = true
        return
      }

      // 获取选中的教师id列表
      const ids = this.ids
      if (!ids || ids.length === 0) {
        this.$message.error('请选择一条记录')
        return
      }
      if (ids.length > 1) {
        this.$message.error('只能选择一条记录')
        return
      }
      // 获取教师详细信息 ，成功后打开modal
      getById(ids[0]).then(({ data }) => {
        this.modalData = data
        // 打开modal
        this.modalModel = model
        this.modalTitle = model === 'Edit' ? '教师信息编辑' : '教师信息详情'
        this.showModal = true
      }).catch((err) => {
        console.log(err)
        this.$message.error('获取选中教师详细信息失败')
      })
    },
    // 关闭教师信息编辑/新增modal
    closeTeacherInfoModal() {
      this.showModal = false
      // 重置modal数据
      this.activename = 'first'
      this.modalData = getDefaultModalData()
    },
    // 点击modal取消按钮
    modalCancelHandler() {
      this.closeTeacherInfoModal()
    },
    // 点击modal提交按钮
    modalSubmitHandler() {
      if (this.modalModel === 'Edit') {
        this.updateTeacherInfo()
      } else if (this.modalModel === 'Create') { this.createTeacherInfo() }
    },
    // 头像图片上传前handler
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 头像图片上传处理handler
    uploadTeaPhoto(item) {
      console.log(item)
      const formData = new FormData()
      formData.append('photo', item.file)
      formData.append('uid', this.ids[0] | '')
      this.viewLoading = true
      uploadTeacherPhoto(formData).then((res) => {
        this.viewLoading = false
        this.$message.success(res.message)
        // 将新的photo路径放到表单数据中
        this.modalData.photoUrl = res.data
      }).catch((err) => {
        this.viewLoading = false
        console.log(err)
      })
    },
    // 创建教师信息
    createTeacherInfo() {
      create(this.modalData).then((res) => {
        this.$message.success(res.message)
        // 刷新数据
        this.refreshTeacherInfo()
        // 关闭modal
        this.closeTeacherInfoModal()
      }).catch(err => {
        console.log(err)
        // 关闭modal
        this.closeTeacherInfoModal()
      })
    },
    // 修改教师信息
    updateTeacherInfo() {
      update(this.modalData).then((res) => {
        this.$message.success(res.message)
        // 刷新数据
        this.refreshTeacherInfo()
        // 关闭modal
        this.closeTeacherInfoModal()
      }).catch(err => {
        console.log(err)
        // 关闭modal
        this.closeTeacherInfoModal()
      })
    },
    // 批量删除教师信息(逻辑删除)
    batchDeleteTeacher() {
      if (this.ids === null || this.ids.length < 1) {
        this.$message.error('请至少选择一条记录')
        return
      }
      this.$confirm('请确认是否删除？').then(() => {
        deleteByIds(this.ids).then(res => {
          this.$message.success(res.message)
          // 刷新数据
          this.refreshTeacherInfo()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message.info('删除已取消')
      })
    }
  }
}

</script>

<style scoped>
  .avatar-uploader {
    border: 1px dashed #a9a9a9;
    width: 100px;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
